window.EventMgr = class EventMgr {
    constructor() {
        this.listeners = [];
    }

    send(name, data) {
        let listeners = [];

        for (let lt of this.listeners) {
            listeners.push(lt);
        }

        for (let lt of listeners) {
            if (lt.name != name) {
                continue;
            }

            let destroyed = false;
            try {
                destroyed = lt.callback(name, data);
            } catch (error) {
                console.error(error);
            }

            if (destroyed) {
                for (let i = this.listeners.length - 1; i >= 0; i--) {
                    if (lt == this.listeners[i]) {
                        this.listeners.splice(i, 1);
                    }
                }
            }
        }
    }

    addListener(lt) {
        this.listeners.push(lt);
    }

    removeListener(name, callback) {
        for (let i = this.listeners.length - 1; i >= 0; i--) {
            let lt = this.listeners[i];

            if (callback == lt.callback && (!name || name == lt.name)) {
                this.listeners.splice(i, 1);
            }
        }
    }
};
